<template>
  <div class="chart-container">
    <p class="chart-title">炉体热负荷分段呈现图</p>
    <div ref="chartElement" class="chart"></div>
  </div>
</template>

<script>
import * as echarts from "echarts";

export default {
  name: "TemperatureChart",
  props: {
    // Base category data (passed once or updated if categories change)
    baseCategories: {
      type: Array,
      default: () => []
    },
    // Current prediction data
    currentData: {
      type: Object,
      default: () => ({ yAxisData: [], percentage: [], yLabel: [] })
    },
    selectedLegend: {
      type: Array,
      default: () => []
    },
  },
  data() {
    return {
      chartInstance: null,
      options: { // Base options structure
        toolbox: {
          show: false,
          feature: {
            dataZoom: { yAxisIndex: 'none' },
            dataView: { readOnly: true },
            saveAsImage: {}
          },
          top: '5%', // Adjusted top position
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' },
          formatter: function(params) {
            let result = params[0].axisValue + '<br/>';
            params.forEach(item => {
              let value;
              if (item.seriesType === 'line') {
                value = (item.value !== undefined && item.value !== null) ? item.value + '×10MJ/h' : 'N/A';
              } else if (item.seriesType === 'bar'){
                value = (item.value !== undefined && item.value !== null) ? item.value + '%' : 'N/A';
              }
              result += item.marker + item.seriesName + ': ' + value + '<br/>';
            });
            return result;
          }
        },
        grid: {
          left: '1%',
          right: '8%',
          bottom: '5%',
          top: '12%', // Adjusted top to accommodate toolbox/legend
          containLabel: true,
          borderColor: '#000',
          borderWidth: 1.5,
          show: true
        },
        xAxis: [
          {
            type: 'value',
            name: '热负荷(×10MJ/h)',
            nameRotate: 0, // 保持水平
            nameLocation: 'middle', // 名称位置
            nameGap: 25, // Adjusted gap
            axisLabel: { formatter: '{value}' },
            axisLine: { lineStyle: { color: '#000', type: 'solid', width: 2 } },
            splitLine: { show: true, lineStyle: { color: '#ccc', type: 'solid', width: 1 } }, // Lighter grid lines
            boundaryGap: [0, 0.01],
            position: 'bottom'
          },
          {
            type: 'value',
            name:'热量占比',
            nameRotate: 0, // 保持水平
            nameLocation: 'middle', // Position name at the end
            nameGap: 25, // Adjusted gap
            axisLabel: { formatter: '{value}%' },
            max: 100,
            boundaryGap: [0, 0.01],
            position: 'top',
            axisLine: { lineStyle: { color: '#000', type: 'solid', width: 2 } },
            splitLine: { show: true, lineStyle: { color: '#ccc', type: 'solid', width: 1 } }, // Lighter grid lines
          }
        ],
        yAxis: [
          {
            type: 'category',
            data: ['CP01~10', 'CP11~20', 'CP21~30', 'CP31~42', 'CP43~54','R段'], // Will be populated by props
            inverse: true,
            axisTick: { show: false },
            axisLine: { show:true, lineStyle: { color: '#000', type: 'solid', width: 2 } },
            splitLine: { show: true, lineStyle: { color: '#ccc', type: 'solid', width: 0.5 } } // Lighter grid lines
          }
        ],
        legend: {
          type: 'scroll',
          data: ['当前热负荷'],
          top: '0%', // Adjusted top position
          textStyle: { fontSize: 12 }, // Slightly smaller legend text
          width: '100%', // Adjust width
          pageButtonItemGap: 4,
          pageButtonGap: 2,
          pageButtonPosition: 'end',
          pageIconColor: '#000',
          pageIconInactiveColor: '#aaa',
          pageTextStyle: { color: '#000', fontSize: 10 },
          selected: {} // To manage selected state
        },
        series: [], // Will be populated dynamically
        // Define a base color palette
        color: [
            '#0037fc',
          '#82daff',
          '#a0c782',
          '#caa5ce',
          '#93acc4',
          '#f8d3a3',
          '#f8a3a3',
          '#b7537b'
        ]
      }
    };
  },
  mounted() {
    this.initChart();
    window.addEventListener('resize', this.handleResize);
    this.updateChart(); // Initial update
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
    this.chartInstance?.dispose();
  },
  watch: {
    // Watch for changes in props and update the chart
    baseCategories: {
      deep: true,
      handler() {
        this.updateChart();
      }
    },
    currentData: {
      deep: true,
      handler() {
        this.updateChart();
      }
    },
    selectedLegend: {
      deep: true,
      handler() {
        this.updateChart();
      }
    }
  },
  methods: {
    getLabel(str){
      const match = str.match(/[0-9A-Z]/);
      // 如果匹配成功，返回第一个匹配的字符；否则返回 null（或自定义默认值）
      return match ? match[0] : null;
    },
    initChart() {
      if (!this.$refs.chartElement) return;
      this.chartInstance = echarts.init(this.$refs.chartElement);
      // Set initial options structure (without dynamic data yet)
      this.chartInstance.setOption(this.options);
    },
    updateChart() {
      if (!this.chartInstance) return;

      const newSeries = [];
      const newLegendData = [];

      // --- Add Current Data Series FIRST ---
      const currentName = '当前热负荷';
      if (this.currentData && this.currentData.yAxisData && this.currentData.yAxisData.length > 0) {
        newSeries.push({
          name: currentName,
          type: 'line',
          data: this.currentData.yAxisData,
          smooth: true,
          symbol: 'circle',
          symbolSize: 8,
          itemStyle: { color: this.options.color[0] }, // Use first color for current
          xAxisIndex: 0
        });
        newSeries.push({
          name: currentName,
          type: 'bar',
          data: this.currentData.percentage,
          barWidth: '8%',
          barCategoryGap: '2%',
          label: { show: false },
          itemStyle: { color: this.options.color[0] }, // Use first color for current
          xAxisIndex: 1
        });
        newLegendData.push(currentName);
      }

      // --- Add Base Category Series AFTER current data ---
      this.baseCategories.forEach((category, index) => {
        const categoryName = this.getLabel(category.name);
        const lineData = category.lineData.slice().reverse(); // Reverse for chart display
        const barData = category.barData.slice().reverse();   // Reverse for chart display

        // Add Line Series for base category
        newSeries.push({
          name: categoryName,
          type: 'line',
          data: lineData,
          smooth: true,
          lineStyle: { type: 'dashed' },
          symbol: 'circle',
          symbolSize: 5,
          xAxisIndex: 0,
          // Use colors from the palette, cycling if necessary
          itemStyle: { color: this.options.color[(index + 1) % this.options.color.length] }
        });

        // Add Bar Series for base category
        newSeries.push({
          name: categoryName,
          type: 'bar',
          barWidth: '8%',
          barCategoryGap: '2%',
          data: barData,
          label: { show: false },
          xAxisIndex: 1,
          // Use colors from the palette, cycling if necessary
          itemStyle: { color: this.options.color[(index + 1) % this.options.color.length] }
        });

        newLegendData.push(this.getLabel(categoryName));
        // Keep existing selection state or default to true (initially show)

      });

      const option = this.chartInstance.getOption();
      const legendData = option.legend[0].data || [];
      const selectedState = {};
      legendData.forEach(name => {
        selectedState[name] = this.selectedLegend.includes(name);
      });
      selectedState['当前热负荷'] = true;

      // --- Update Options and Set ---
      this.chartInstance.setOption({
        // yAxis: [{ // Update YAxis data
        //   data: this.currentData?.yLabel // Use current labels or fallback
        // }],
        legend: {
          data: [...new Set(newLegendData)], // Ensure unique legend items
          selected: selectedState // Apply selection state
        },
        series: newSeries // Set the combined series data
      }, { notMerge: false }); // Use notMerge: false to allow legend selection persistence generally, but be mindful if structure changes drastically
    },
    handleResize() {
      this.chartInstance?.resize();
    }
  }
};
</script>

<style scoped>
.chart-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 200px; /* Ensure minimum height */
}
.chart-title {
  text-align: center;
  margin: 2px 0; /* 减小上下边距 */
  font-size: 0.9em; /* 减小字体大小 */
  font-weight: bold;
  color: #333;
  line-height: 1.2; /* 减小行高 */
}
.chart {
  flex-grow: 1;
  width: 100%;
  height: 100%; /* Let container control height */
}
</style>
